package cn.tedu.jdbc;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Scanner;

public class JDBCReg {
    public static void main(String[] args) {
        try (Connection connection = DBUtil.getConnection();){
            Scanner scanner = new Scanner(System.in);
            String username;
            while (true){
                System.out.println("请输入用户名：");
                username = scanner.nextLine();
                String sql="SELECT nickname FROM userinfo WHERE username=?";
                PreparedStatement preparedStatement = connection.prepareStatement(sql);
                preparedStatement.setString(1,username);
                ResultSet r=preparedStatement.executeQuery();
                if(r.next()){
                    System.out.println("用户名已存在,请重新输入");
                }else{
                    System.out.println("用户名可用");
                    break;
                }
            }
            System.out.println("请输入密码：");
            String password = scanner.nextLine();
            System.out.println("请输入昵称：");
            String nickname=scanner.nextLine();
            System.out.println("请输入年龄：");
            Integer age=scanner.nextInt();
            String sql1="INSERT INTO userinfo(password,nickname,age,username) VALUES(?,?,?,?)";
            PreparedStatement ps = connection.prepareStatement(sql1);
            ps.setString(1,password);
            ps.setString(2,nickname);
            ps.setInt(3,age);
            ps.setString(4,username);
            int i = ps.executeUpdate();
            if(i>0){
                System.out.println("注册成功");
            }else{
                System.out.println("注册失败");
            }


        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
    }
}
